 package com.stardata.liangshisq.tcslmon.util;

 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JavaType;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import org.jetbrains.annotations.NotNull;

 import java.util.List;

 public class JSONUtil
 {
   private static ObjectMapper mapper = null;
 
   public static ObjectMapper jsonMapper() {
     if (mapper == null) {
       mapper = new ObjectMapper();
     }
     return mapper;
   }
 
   public static JsonNode readTree(String jsonStr) throws JsonProcessingException {
     return jsonMapper().readTree(jsonStr);
   }
 
   public static ObjectNode createObjectNode() {
     return jsonMapper().createObjectNode();
   }

   @NotNull
   public static String toJSONString(Object object) {
     try {
       return jsonMapper().writeValueAsString(object); }
     catch (JsonProcessingException ignored) { }
     return "";
   }
 
   public static <T> T parseObject(String jsonStr, Class<T> valueType) throws JsonProcessingException
   {
     return jsonMapper().readValue(jsonStr, valueType);
   }
 
   public static <T> List<T> parseList(String jsonStr, Class<T> valueType) {
     JavaType javaType = jsonMapper().getTypeFactory().constructCollectionType(List.class, valueType);
     try {
       return (List<T>)jsonMapper().readValue(jsonStr, javaType); }
     catch (Exception ignored) {}
     return null;
   }
 
   public static Long getLong(JsonNode jsonNode, String fieldName)
   {
     JsonNode node = jsonNode.get(fieldName);
     if (node == null) return null;
     String str = node.asText();
     try {
       return Long.parseLong(str); }
     catch (NumberFormatException ignored) {
     }
     return null;
   }
 }
